"""
校园新生指引程序 - 技术拓展框架
包含主题切换、API接口等扩展功能
"""

import tkinter as tk
from tkinter import ttk
from typing import Dict, Any, Optional, Callable
import json
import requests
from abc import ABC, abstractmethod


class ThemeManager:
    """主题管理器 - 支持轻量化主题切换"""
    
    def __init__(self):
        self.themes = {
            'light': {
                'bg_color': '#f0f8ff',
                'fg_color': '#2c3e50',
                'accent_color': '#3498db',
                'frame_bg': '#ecf0f1',
                'text_bg': '#ffffff',
                'text_fg': '#2c3e50'
            },
            'dark': {
                'bg_color': '#2c3e50',
                'fg_color': '#ecf0f1',
                'accent_color': '#3498db',
                'frame_bg': '#34495e',
                'text_bg': '#2c3e50',
                'text_fg': '#ecf0f1'
            },
            'blue': {
                'bg_color': '#e3f2fd',
                'fg_color': '#1565c0',
                'accent_color': '#1976d2',
                'frame_bg': '#bbdefb',
                'text_bg': '#ffffff',
                'text_fg': '#0d47a1'
            },
            'green': {
                'bg_color': '#e8f5e8',
                'fg_color': '#2e7d32',
                'accent_color': '#4caf50',
                'frame_bg': '#c8e6c9',
                'text_bg': '#ffffff',
                'text_fg': '#1b5e20'
            }
        }
        self.current_theme = 'light'
    
    def apply_theme(self, root: tk.Tk, style: ttk.Style, theme_name: str):
        """应用主题"""
        if theme_name not in self.themes:
            theme_name = 'light'
        
        self.current_theme = theme_name
        theme = self.themes[theme_name]
        
        # 配置根窗口
        root.configure(bg=theme['bg_color'])
        
        # 配置样式
        style.configure('Title.TLabel', 
                       font=('微软雅黑', 16, 'bold'), 
                       foreground=theme['fg_color'])
        style.configure('Subtitle.TLabel', 
                       font=('微软雅黑', 12, 'bold'), 
                       foreground=theme['fg_color'])
        style.configure('Modern.TFrame', 
                       background=theme['frame_bg'])
        style.configure('Modern.TLabelframe', 
                       background=theme['frame_bg'], 
                       relief='solid', 
                       borderwidth=1)
        style.configure('Modern.TLabelframe.Label', 
                       font=('微软雅黑', 11, 'bold'), 
                       foreground=theme['fg_color'])
        style.configure('Accent.TButton', 
                       font=('微软雅黑', 10), 
                       background=theme['accent_color'], 
                       foreground='white')
        style.map('Accent.TButton', 
                 background=[('active', self._darken_color(theme['accent_color']))])
    
    def _darken_color(self, color: str, factor: float = 0.8) -> str:
        """加深颜色"""
        # 简化的颜色加深逻辑
        if color.startswith('#'):
            r = int(color[1:3], 16)
            g = int(color[3:5], 16)
            b = int(color[5:7], 16)
            r = int(r * factor)
            g = int(g * factor)
            b = int(b * factor)
            return f'#{r:02x}{g:02x}{b:02x}'
        return color
    
    def get_theme_names(self) -> list:
        """获取可用主题列表"""
        return list(self.themes.keys())


class CampusMapAPI(ABC):
    """校园地图API抽象基类 - 预留接口"""
    
    @abstractmethod
    def sync_map_data(self, local_map) -> bool:
        """同步地图数据"""
        pass
    
    @abstractmethod
    def get_building_info(self, building_id: str) -> Optional[Dict]:
        """获取建筑信息"""
        pass
    
    @abstractmethod
    def search_points(self, keyword: str) -> list:
        """搜索点位"""
        pass


class MockCampusMapAPI(CampusMapAPI):
    """模拟校园地图API - 用于演示和测试"""
    
    def __init__(self, api_endpoint: str = "https://api.campus.edu/map"):
        self.api_endpoint = api_endpoint
        self.mock_data = {
            "buildings": {
                "B001": {
                    "name": "行政楼",
                    "coordinates": {"x": 100, "y": 200},
                    "functions": ["行政办公", "教务处"],
                    "description": "学校行政中心"
                },
                "B002": {
                    "name": "教学楼A",
                    "coordinates": {"x": 150, "y": 180},
                    "functions": ["教学", "教室"],
                    "description": "主要教学楼"
                }
            }
        }
    
    def sync_map_data(self, local_map) -> bool:
        """模拟同步地图数据"""
        try:
            # 模拟API调用
            print(f"正在从 {self.api_endpoint} 同步地图数据...")
            
            # 将模拟数据添加到本地地图
            for building_id, building_info in self.mock_data["buildings"].items():
                # 这里可以添加实际的点位创建逻辑
                print(f"同步建筑: {building_info['name']}")
            
            return True
        except Exception as e:
            print(f"同步失败: {e}")
            return False
    
    def get_building_info(self, building_id: str) -> Optional[Dict]:
        """获取建筑信息"""
        return self.mock_data["buildings"].get(building_id)
    
    def search_points(self, keyword: str) -> list:
        """搜索点位"""
        results = []
        for building_id, building_info in self.mock_data["buildings"].items():
            if (keyword.lower() in building_info["name"].lower() or 
                any(keyword.lower() in func.lower() for func in building_info["functions"])):
                results.append({
                    "id": building_id,
                    "name": building_info["name"],
                    "type": "building"
                })
        return results


class ExtensionManager:
    """扩展管理器 - 统一管理所有扩展功能"""
    
    def __init__(self):
        self.theme_manager = ThemeManager()
        self.api_client: Optional[CampusMapAPI] = None
        self.extensions = {}
    
    def register_extension(self, name: str, extension: Any):
        """注册扩展"""
        self.extensions[name] = extension
    
    def get_extension(self, name: str) -> Optional[Any]:
        """获取扩展"""
        return self.extensions.get(name)
    
    def setup_api_client(self, api_class: type, **kwargs):
        """设置API客户端"""
        try:
            self.api_client = api_class(**kwargs)
            return True
        except Exception as e:
            print(f"API客户端设置失败: {e}")
            return False
    
    def create_theme_menu(self, parent, apply_callback: Callable):
        """创建主题选择菜单"""
        theme_menu = tk.Menu(parent, tearoff=0)
        
        for theme_name in self.theme_manager.get_theme_names():
            theme_menu.add_command(
                label=theme_name.capitalize(),
                command=lambda t=theme_name: apply_callback(t)
            )
        
        return theme_menu


# 使用示例
if __name__ == "__main__":
    # 主题管理器使用示例
    theme_mgr = ThemeManager()
    print("可用主题:", theme_mgr.get_theme_names())
    
    # API客户端使用示例
    api_client = MockCampusMapAPI()
    print("建筑信息:", api_client.get_building_info("B001"))
    print("搜索点位:", api_client.search_points("教学"))
    
    # 扩展管理器使用示例
    ext_mgr = ExtensionManager()
    ext_mgr.register_extension("theme", theme_mgr)
    ext_mgr.register_extension("api", api_client)
    
    print("扩展管理器已初始化")
